package com.loveshes.filter;

import com.loveshes.constants.Constants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.slf4j.MDC;

import java.util.Map;
import java.util.UUID;

import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER;

/**
 * @author wangz4
 * @date 2024/12/26 20:26
 */
@Activate(group = PROVIDER, order = -9000)
public class ReqNoProviderFilter implements Filter {
    
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        // 从上下文对象中取出跟踪序列号值
        String existsTraceId = invocation.getAttachment(Constants.MDC_KEY_TRACE_ID);
        
        // 然后将序列号值设置到请求对象中
        RpcContext.getServerAttachment().setAttachment(Constants.MDC_KEY_TRACE_ID, existsTraceId);
        RpcContext.getClientAttachment().setAttachment(Constants.MDC_KEY_TRACE_ID, existsTraceId);
        try {
            // 并且将序列号设置到日志打印器中，方便在日志中体现出来
            MDC.put(Constants.MDC_KEY_TRACE_ID, existsTraceId);
            // 继续后面过滤器的调用
            return invoker.invoke(invocation);
        } finally {
            MDC.clear();
        }
    }
    
}
